package stockQuoteGetter;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class StockQuoteGetter
{
	private URL connectionBase;
	private URLConnection connection;
	private final String nameValuePairBase = "s=";
	private final String searchStringFront = "<span id=\"yfs_l84_";
	private final String searchStringBack = "\">";
	
	
	public StockQuoteGetter () throws MalformedURLException
	{

		this.connectionBase = new URL ("http://finance.yahoo.com/q?");

	}
	
	private void createConnection () throws IOException
	{
		this.connection = this.connectionBase.openConnection();
		this.connection.setDoInput(true);
		this.connection.setDoOutput(true);
	}
	
	public double getQuote (String s) throws IOException
	{
		String nameValuePair = this.nameValuePairBase.concat(s);
		byte[] buffer = new byte [1024];
		int numberRead;
		double returnVal = -1.0;
				
		this.createConnection();
		OutputStream out = this.connection.getOutputStream();
		out.write(nameValuePair.getBytes());
		BufferedInputStream bin = new BufferedInputStream (this.connection.getInputStream());
		
		while (((numberRead = bin.read(buffer)) != -1) &&
				(returnVal == -1.0))
		{
			String readData = new String(buffer, 0, numberRead);
			
			returnVal = this.getPrice(readData, s);
		}
		
		out.close();
		bin.close();
		
		return returnVal;
	}
	
	private double getPrice(String s, String currentSymbol)
	{
		String searchString = this.searchStringFront + currentSymbol + this.searchStringBack;
		int index = s.indexOf(searchString);
		
		if(index != -1)
		{
			String workingString = "";
			
			for(int i = index + searchString.length(); s.charAt(i) != '<' &&  i < s.length(); ++i)
			{
				if(s.charAt(i) != ',')
					workingString += s.charAt(i);
			}
			
			return Double.parseDouble(workingString);
		}
		
		return -1.0;
	}
	
}
